// 智能化灌溉模块的主要功能实现
class SmartIrrigation {
    constructor() {
        this.initializeElements();
        this.initializeState();
        this.initializeEventListeners();
        this.initializeCharts();
        this.startAutoMonitoring();
    }

    // 初始化DOM元素
    initializeElements() {
        // 系统状态
        this.systemStatusEl = document.getElementById('ai-system-status');
        this.suggestedAmountEl = document.getElementById('suggested-amount');
        this.suggestedTimeEl = document.getElementById('suggested-time');
        this.decisionCountEl = document.getElementById('decision-count');

        // 控制按钮
        this.autoModeBtn = document.getElementById('auto-mode');
        this.manualModeBtn = document.getElementById('manual-mode');
        this.executeBtn = document.getElementById('execute-btn');
        this.cancelBtn = document.getElementById('cancel-btn');

        // 高级控制选项
        this.intensitySelect = document.getElementById('irrigation-intensity');
        this.autoThreshold = document.getElementById('auto-threshold');
        this.prioritySelect = document.getElementById('irrigation-priority');
        this.thresholdValue = document.querySelector('.threshold-value');

        // 图表容器
        this.moistureChartCtx = document.getElementById('moistureMonitorChart').getContext('2d');
        this.effectChartCtx = document.getElementById('irrigationEffectChart').getContext('2d');
    }

    // 初始化状态
    initializeState() {
        this.autoMode = true;
        this.isExecuting = false;
        this.thresholds = {
            moisture: {
                min: 45,
                max: 75
            },
            temperature: {
                min: 15,
                max: 35
            }
        };
        this.currentData = {
            moisture: 48.2,
            temperature: 26,
            humidity: 65,
            rainfall: {
                probability: 10
            }
        };
    }

    // 初始化事件监听器
    initializeEventListeners() {
        // 模式切换
        this.autoModeBtn.addEventListener('click', () => this.enableAutoMode());
        this.manualModeBtn.addEventListener('click', () => this.enableManualMode());

        // 执行控制
        this.executeBtn.addEventListener('click', () => this.confirmExecution());
        this.cancelBtn.addEventListener('click', () => this.confirmCancellation());

        // 高级控制选项
        this.intensitySelect.addEventListener('change', () => this.updateIrrigationSuggestion());
        this.autoThreshold.addEventListener('input', (e) => {
            this.thresholdValue.textContent = `${e.target.value}%`;
            this.updateIrrigationSuggestion();
        });
        this.prioritySelect.addEventListener('change', () => this.updateIrrigationSuggestion());

        // 时间范围选择
        document.querySelectorAll('.time-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                document.querySelectorAll('.time-btn').forEach(b => b.classList.remove('active'));
                e.target.classList.add('active');
                this.updateCharts(e.target.dataset.range);
            });
        });
    }

    // 初始化图表
    initializeCharts() {
        // 土壤墒情监测图表
        this.moistureChart = new Chart(this.moistureChartCtx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [{
                    label: '土壤墒情',
                    data: [],
                    borderColor: '#1890ff',
                    backgroundColor: 'rgba(24, 144, 255, 0.1)',
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100
                    }
                }
            }
        });

        // 灌溉效果图表
        this.effectChart = new Chart(this.effectChartCtx, {
            type: 'bar',
            data: {
                labels: ['改善率', '水分利用率', '节水率'],
                datasets: [{
                    data: [23.5, 89.2, 32.8],
                    backgroundColor: [
                        'rgba(24, 144, 255, 0.6)',
                        'rgba(82, 196, 26, 0.6)',
                        'rgba(250, 173, 20, 0.6)'
                    ]
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100
                    }
                }
            }
        });
    }

    // 启动自动监控
    startAutoMonitoring() {
        this.monitoringInterval = setInterval(async () => {
            if (this.autoMode) {
                await this.checkAndAutoExecute();
            }
            await this.updateData();
        }, 5 * 60 * 1000); // 每5分钟检查一次
    }

    // 更新数据
    async updateData() {
        try {
            // 模拟获取实时数据
            const data = await this.fetchRealtimeData();
            this.currentData = data;

            // 更新图表
            this.updateCharts();

            // 更新建议
            this.updateIrrigationSuggestion();
        } catch (error) {
            console.error('更新数据失败:', error);
            this.setSystemStatus('error', '数据更新失败');
        }
    }

    // 模拟获取实时数据
    async fetchRealtimeData() {
        // 模拟API调用
        return new Promise(resolve => {
            setTimeout(() => {
                resolve({
                    moisture: 48.2 + (Math.random() * 2 - 1),
                    temperature: 26 + (Math.random() * 2 - 1),
                    humidity: 65 + (Math.random() * 5 - 2.5),
                    rainfall: {
                        probability: Math.floor(Math.random() * 20)
                    }
                });
            }, 1000);
        });
    }

    // 更新图表
    updateCharts(timeRange = '6h') {
        const now = new Date();
        const labels = [];
        const moistureData = [];
        const points = timeRange === '6h' ? 12 : timeRange === '24h' ? 24 : 7;
        const interval = timeRange === '6h' ? 30 : timeRange === '24h' ? 60 : 1440;

        for (let i = points - 1; i >= 0; i--) {
            const time = new Date(now - i * interval * 60000);
            labels.push(timeRange === '7d' ? 
                time.toLocaleDateString() : 
                time.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'})
            );
            moistureData.push(45 + Math.random() * 10);
        }

        this.moistureChart.data.labels = labels;
        this.moistureChart.data.datasets[0].data = moistureData;
        this.moistureChart.update();
    }

    // 更新灌溉建议
    updateIrrigationSuggestion() {
        const { moisture } = this.currentData;
        const threshold = parseInt(this.autoThreshold.value);
        const intensity = this.intensitySelect.value;
        const priority = this.prioritySelect.value;

        let suggestedAmount = 25;
        if (moisture < threshold) {
            suggestedAmount = intensity === 'low' ? 20 : intensity === 'high' ? 30 : 25;
        }

        this.suggestedAmountEl.textContent = suggestedAmount;
        this.suggestedTimeEl.textContent = '04:00';
    }

    // 启用自动模式
    enableAutoMode() {
        this.autoMode = true;
        this.autoModeBtn.classList.add('active');
        this.manualModeBtn.classList.remove('active');
        this.setSystemStatus('normal', '自动模式已启用');
    }

    // 启用手动模式
    enableManualMode() {
        this.autoMode = false;
        this.manualModeBtn.classList.add('active');
        this.autoModeBtn.classList.remove('active');
        this.setSystemStatus('normal', '手动模式已启用');
    }

    // 确认执行灌溉
    async confirmExecution() {
        if (this.isExecuting) return;

        const confirmed = await this.showConfirmDialog('确认要执行灌溉方案吗？');
        if (confirmed) {
            this.executeIrrigationPlan();
        }
    }

    // 确认取消灌溉
    async confirmCancellation() {
        if (!this.isExecuting) return;

        const confirmed = await this.showConfirmDialog('确认要取消当前灌溉任务吗？');
        if (confirmed) {
            this.cancelIrrigationPlan();
        }
    }

    // 执行灌溉方案
    async executeIrrigationPlan() {
        if (this.isExecuting) return;

        try {
            this.isExecuting = true;
            this.executeBtn.disabled = true;
            this.cancelBtn.disabled = false;
            this.setSystemStatus('executing', '正在执行灌溉方案');

            // 模拟灌溉过程
            await this.simulateIrrigation();

            this.setSystemStatus('normal', '灌溉完成');
            this.updateDecisionCount(1);
            this.recordDecision({
                time: new Date().toLocaleString(),
                type: this.autoMode ? '自动决策' : '手动决策',
                suggestion: `灌溉${this.suggestedAmountEl.textContent}m³/亩，持续2小时`,
                status: 'success',
                result: '墒情提升15.8%'
            });
        } catch (error) {
            console.error('灌溉执行失败:', error);
            this.setSystemStatus('error', '灌溉执行失败');
        } finally {
            this.isExecuting = false;
            this.executeBtn.disabled = false;
            this.cancelBtn.disabled = true;
        }
    }

    // 取消灌溉方案
    cancelIrrigationPlan() {
        if (!this.isExecuting) return;

        this.isExecuting = false;
        this.executeBtn.disabled = false;
        this.cancelBtn.disabled = true;
        this.setSystemStatus('normal', '灌溉已取消');
    }

    // 模拟灌溉过程
    simulateIrrigation() {
        return new Promise(resolve => {
            setTimeout(resolve, 5000); // 模拟5秒的灌溉过程
        });
    }

    // 更新决策次数
    updateDecisionCount(increment = 1) {
        const currentCount = parseInt(this.decisionCountEl.textContent);
        this.decisionCountEl.textContent = currentCount + increment;
    }

    // 记录决策历史
    recordDecision(decision) {
        const historyBody = document.getElementById('decision-history');
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${decision.time}</td>
            <td>${decision.type}</td>
            <td>${decision.suggestion}</td>
            <td><span class="status-tag ${decision.status === 'success' ? 'success' : 'warning'}">${decision.status === 'success' ? '已完成' : '已取消'}</span></td>
            <td>${decision.result || '-'}</td>
        `;
        historyBody.insertBefore(row, historyBody.firstChild);
    }

    // 设置系统状态
    setSystemStatus(type, message) {
        this.systemStatusEl.className = `status-tag ${type}`;
        this.systemStatusEl.textContent = message;
    }

    // 显示确认对话框
    showConfirmDialog(message) {
        return new Promise(resolve => {
            const confirmed = window.confirm(message);
            resolve(confirmed);
        });
    }

    // 自动检查和执行
    async checkAndAutoExecute() {
        if (!this.autoMode || this.isExecuting) return;

        const { moisture } = this.currentData;
        const threshold = parseInt(this.autoThreshold.value);

        if (moisture < threshold) {
            await this.executeIrrigationPlan();
        }
    }
}

// 初始化智能灌溉系统
document.addEventListener('DOMContentLoaded', () => {
    window.smartIrrigation = new SmartIrrigation();
}); 